// 监听来自 content script 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    switch (request.action) {
        case 'captureVisible':
            captureVisibleArea(sender.tab.id);
            break;
        case 'captureFull':
            captureFullPage(sender.tab.id);
            break;
        case 'captureSelection':
            captureSelection(sender.tab.id, request.area);
            break;
    }
});

// 截取可见区域
async function captureVisibleArea(tabId) {
    try {
        const dataUrl = await chrome.tabs.captureVisibleTab();
        downloadScreenshot(dataUrl);
    } catch (error) {
        console.error('截图失败：', error);
    }
}

// 截取整个页面
async function captureFullPage(tabId) {
    try {
        // 获取页面完整高度
        const [{ result: pageHeight }] = await chrome.scripting.executeScript({
            target: { tabId },
            func: () => Math.max(
                document.documentElement.scrollHeight,
                document.body.scrollHeight
            )
        });

        // 截取可见区域
        const dataUrl = await chrome.tabs.captureVisibleTab();
        downloadScreenshot(dataUrl);
    } catch (error) {
        console.error('截图失败：', error);
    }
}

// 截取选择区域
async function captureSelection(tabId, area) {
    try {
        const dataUrl = await chrome.tabs.captureVisibleTab();
        const img = new Image();
        img.src = dataUrl;

        img.onload = () => {
            const canvas = document.createElement('canvas');
            canvas.width = area.width;
            canvas.height = area.height;

            const ctx = canvas.getContext('2d');
            ctx.drawImage(
                img,
                area.left,
                area.top,
                area.width,
                area.height,
                0,
                0,
                area.width,
                area.height
            );

            downloadScreenshot(canvas.toDataURL());
        };
    } catch (error) {
        console.error('截图失败：', error);
    }
}

// 下载截图
function downloadScreenshot(dataUrl) {
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    chrome.downloads.download({
        url: dataUrl,
        filename: `screenshot-${timestamp}.png`,
        saveAs: true
    });
}